package server.user.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @PostMapping("login")
    public SaResult login(@RequestParam(required = false) String username, @RequestParam(required = false) String password) {
        if (StrUtil.isBlank(username)) {
            return SaResult.error("登录用户名不能为空");
        }
        if (StrUtil.isBlank(password)) {
            return SaResult.error("登录密码不能为空");
        }
        if ("admin".equals(username) && "admin".equals(password)) {
            StpUtil.login(10001);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return SaResult.ok("登录成功！").setData(tokenInfo);
        }
        return SaResult.error("登录失败！用户名或密码错误！");
    }

    /**
     * 忘记密码--找回密码
     */
    @PostMapping("pass/back")
    public SaResult passBack(@RequestParam(required = false) String mobile, @RequestParam(required = false) String newPass) {
        if (StrUtil.isBlank(mobile)) {
            return SaResult.error("手机号不能为空");
        }
        if (StrUtil.isBlank(newPass)) {
            return SaResult.error("新密码不能为空");
        }
        boolean isLogin = StpUtil.isLogin();
        if (isLogin) {
            StpUtil.logout();
        }
        return SaResult.ok();
    }


    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
